// 引入第三方模块
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const session = require("express-session");

// 创建连接池
var pool = mysql.createPool({
    host:"127.0.0.1",
    user:"root",
    password:"",
    port:3306,
    database:"noval",
    connectionLimit:15
});

// 创建服务器
var server = express();
//跨域
server.use(cors({
    origin:[""],
    credentials:true
}))

// session
server.use(session({
    secret:"128位字符串",
    resave:true,
    saveUninitialized:true
}));

//静态目录
server.use(express.static("public"));
// 监听端口
server.listen(3000);

// server.get("/login",(req,res)=>{
//     // 获得参数
//     var obj = req.query;
//     var uname = obj.uname;
//     var upwd = obj.upwd;
//     //编写sql
//     var sql = "SELECT id FROM xz_login WHERE uname=? AND upwd = md5(?)";
//     pool.query(sql,[uname,upwd],(err,result)=>{
//         if(err) throw err;
//         if(result.length > 0){
//             // 将用户的uid保存到sassion对象中
//             req.session.uid = result[0].id;
//             res.send({node:1,msg:"登录成功"})
//         }else{
//             res.send({node:-1,msg:"用户名或密码错误"})
//         }
//     })
// });


server.get("/getbooks" ,( req, res ) => {
    var sql = "SELECT * FROM book";
    pool.query(sql, ( err, result ) => {
        if(err) throw err;
        if( result.length > 0 ){
            res.send(result);
        }
    });
});


server.get("/getbookDetails" ,( req, res ) => {
    var obj = req.query;
    var bookid = obj.id;
    var start = obj.start;
    if( !start ){
        start = 0;
    }
    var sql = "SELECT * FROM chapter WHERE bookID=" + bookid +" LIMIT "+ start +",10";
    pool.query(sql, [bookid], ( err, result ) => {
        if(err) throw err;
        if( result.length > 0 ){
            res.send(result);
        }
    });
});


server.get("/getbookTotalPages" ,( req, res ) => {
    var obj = req.query;
    var bookid = obj.id;
    var sql = "SELECT count(*) FROM chapter WHERE bookID=" + bookid;
    pool.query(sql, [bookid], ( err, result ) => {
        if(err) throw err;
        if( result.length > 0 ){
            res.send(result);
        }
    });
});


